<?php

namespace app\common\model\worker;

use app\common\model\BaseModel;
use app\common\model\offer\GoodsConfigModel;
use app\common\model\offer\GoodsDetailModel;
use app\common\model\offer\GoodsModel;
use helper\Arr;
use helper\Utils;
use think\facade\Db;


class OfferModel extends BaseModel
{
    protected $table = 'offer';


    public function _formatList($list){
        $customerIds = array_column($list,'customer_id');
        $offerSns = array_column($list,'offer_sn');
        $customerList = CustomerModel::where('id','in',$customerIds)->column('*','id');
        $offerList = $this->where('offer_sn','in',$offerSns)->select()->toArray();
        $offerIds = array_column($offerList,'id');
        $offerList = Arr::group($offerList,'offer_sn');
        $detailList = OfferDetailModel::where('offer_id','in',$offerIds)->select()->toArray();
        $detailList = Arr::group($detailList,'offer_id');
        foreach ($list as $k=>$v){
            foreach ($offerList[$v['offer_sn']] as $key=>$offer){
                $detailItem = [];
                foreach ($detailList[$offer['id']] as $kk=>$vv){
                    $vv['goods_config'] = json_decode($vv['goods_config'],true);
                    $detailItem[$key][$vv['goods_bom_id'].'_'.$vv['goods_bom_group']][] = $vv;
                }
                $detail = [];
                foreach ($detailItem[$key] as $kk=>$vv){
                    $detail[$kk] = [
                        'list'=>$vv,
                        'goods_bom_id'=>$vv[0]['goods_bom_id'],
                        'goods_bom_name'=>$vv[0]['goods_bom_name'],
                        'goods_bom_alias'=>$vv[0]['goods_bom_alias'],
                        'detail_total'=>number_format(Arr::sum($vv,'detail_amount'),2)
                    ];
                }
                $offerList[$v['offer_sn']][$key]['detail'] = $detail;
            }
            $v['offer_list'] = $offerList[$v['offer_sn']];
            $v['offer_total'] = number_format(Arr::sum($offerList[$v['offer_sn']],'goods_amount'),2);
            //$v['detail'] = $detail;
            $v['customer_info'] = $customerList[$v['customer_id']];
            $list[$k] = $v;
        }
        return $list;
    }
    /**
     * 添加报价单
     * @param $data
     */
    public function addOffer($data,$adminId){
        $offerData = $data['offer_data'];
        $cellDetail = array_column($offerData,'cell_detail');
        $cellDetail = array_reduce($cellDetail,function($result, $value){
                         return array_merge($result, array_values($value));
                      },[]);
        $goodsDetailIds = array_column($cellDetail,'goods_detail_id');
        $goodsConfigIds = array_column($cellDetail,'cell_id');
        $goodsModel = new GoodsModel();
        $goodsDetailModel = new GoodsDetailModel();
        $goodsConfigModel = new GoodsConfigModel();
        $detailModel = new OfferDetailModel();
        $goodsDetailList = $goodsDetailModel->where('id','in',$goodsDetailIds)->column('*','id');
        $goodsConfigList = $goodsConfigModel->where('id','in',$goodsConfigIds)->column('*','id');
        $goodsList = $goodsModel->column('*','id');
        Db::startTrans();
        try {
            if(!isset($data['offer_sn'])){
                $offerSn = Utils::builderOrderSn();
            }else{
                //编辑报价单操作，删除原先报价数据，重新新建，保留原报价单号
                $offerSn = $data['offer_sn'];
                $offList = $this->where('offer_sn',$data['offer_sn'])->select()->toArray();
                if($offList[0]['order_id']>0) exception('已转订单的报价不能再编辑');
                $this->where('offer_sn',$data['offer_sn'])->delete();
                $detailModel->where('offer_id','in',array_column($offList,'id'))->delete();
            }
            foreach ($offerData as $k=>$v){
                $goodsAmount = 0;
                $detailList = [];
                $goodsData = [
                    'offer_sn'=>$offerSn,
                    'goods_id'=>$v['goods_id'],
                    'goods_name'=>$goodsList[$v['goods_id']]['goods_name'],
                    'goods_alias'=>$v['goods_alias'],
                    'customer_id'=>$data['customer_id'],
                    'goods_remarks'=>$data['goods_remarks'] ?? '',
                ];
                $offerInfo = self::create($goodsData);
                foreach ($v['cell_detail'] as $kk=>$vv){
                    $saleNumber = empty($vv['sale_number'])?0:$vv['sale_number'];
                    $plusNumber1 = empty($vv['plus_number_1'])?0:$vv['plus_number_1'];
                    $plusNumber2 = empty($vv['plus_number_2'])?0:$vv['plus_number_2'];
                    $goodsInfo = $goodsList[$vv['goods_bom_id']];
                    $goodsDetailInfo = $goodsDetailList[$vv['goods_detail_id']];
                    $goodsConfigInfo = $goodsConfigList[$vv['cell_id']];
                    $detailAmount = $goodsDetailInfo['sale_price']*$saleNumber+$goodsDetailInfo['plus_price_1']*$plusNumber1+$goodsDetailInfo['plus_price_2']*$plusNumber2;
                    $goodsAmount+=$detailAmount;
                    $detailInfo = $goodsDetailInfo;
                    unset($detailInfo['id']);
                    $detailInfo['goods_bom_group'] = $vv['goods_bom_group'];
                    $detailInfo['goods_bom_id'] = $vv['goods_bom_id'];
                    $detailInfo['goods_bom_name'] = $goodsInfo['goods_name'];
                    $detailInfo['goods_bom_alias'] = $vv['goods_bom_name'];
                    $detailInfo['goods_config_name'] = $goodsConfigInfo['goods_name'];
                    $detailInfo['goods_config'] = $goodsConfigInfo['goods_config'];
                    $detailInfo['goods_detail_id'] = $vv['goods_detail_id'];
                    $detailInfo['detail_amount'] = $detailAmount;
                    $detailInfo['offer_id'] = $offerInfo['id'];
                    $detailInfo['sale_number'] = $vv['sale_number'];
                    $detailInfo['plus_number_1'] = $vv['plus_number_1'];
                    $detailInfo['plus_number_2'] = $vv['plus_number_2'];
                    $detailList[] = $detailInfo;
                }
                $detailModel->saveAll($detailList);
                $this->where('id',$offerInfo['id'])->update(['goods_amount'=>$goodsAmount]);
            }
            Db::commit();
        } catch (\Exception $e) {
            exception($e->getMessage());
            // 回滚事务
            Db::rollback();
        }
        return $offerInfo;
    }


    public function getInfo($id){
        $info = $this->where('id',$id)->find();
        $info['customer_info'] = CustomerModel::where('id',$info['customer_id'])->find();
        $detailList = OfferDetailModel::where('offer_id',$id)->select()->toArray();
        //$detailList = Arr::group($detailList,'goods_bom_id');
        foreach ($detailList as $k=>$v){
            $v['goods_config'] = json_decode($v['goods_config'],true);
            $detailItem[$v['goods_bom_id'].'_'.$v['goods_bom_group']][] = $v;
        }
        foreach ($detailItem as $k=>$v){
            $detail[$k] = [
                'list'=>$v,
                'goods_bom_id'=>$v[0]['goods_bom_id'],
                'goods_bom_name'=>$v[0]['goods_bom_name'],
                'goods_bom_alias'=>$v[0]['goods_bom_alias'],
                'detail_total'=>Arr::sum($v,'detail_amount')
            ];
        }
        $info['detail'] = $detail;
        return $info;
    }

    public function getOffer($offerSn){
        $offerList = $this->where('offer_sn',$offerSn)->select()->toArray();
        $customerInfo = CustomerModel::where('id',$offerList[0]['customer_id'])->find()->toArray();
        $detailList = OfferDetailModel::where('offer_id','in',array_column($offerList,'id'))->select()->toArray();
        $detailList = Arr::group($detailList,'offer_id');

        foreach ($offerList as $k=>$v){
            $detailItem = [];
            $sku_arr=[];
            foreach ($detailList[$v['id']] as $kk=>$vv){
                foreach ($vv as $attrKey=>$attr){
                    if(preg_match('/^s\d/',$attrKey) && !empty($attr)){
                        $sku_arr[$kk][] = $attr;
                    }
                }
                $vv['sku_arr'] = $sku_arr[$kk];
                $vv['goods_config'] = json_decode($vv['goods_config'],true);
                $detailItem[$vv['goods_bom_id'].'_'.$vv['goods_bom_group']][] = $vv;
            }
            $detail = [];
            foreach ($detailItem as $key=>$item){
                $detail[$key] = [
                    'list'=>$item,
                    'goods_bom_id'=>$item[0]['goods_bom_id'],
                    'goods_bom_name'=>$item[0]['goods_bom_name'],
                    'goods_bom_alias'=>$item[0]['goods_bom_alias'],
                    'detail_total'=>Arr::sum($item,'detail_amount')
                ];
            }
            $offerList[$k]['detail'] = $detail;
        }
        $data =  [
            'offer_sn'=>$offerSn,
            'offer_list'=>$offerList,
            'offer_total'=>Arr::sum($offerList,'goods_amount'),
            'customer_info'=>$customerInfo,
            'goods_remarks'=>$offerList[0]['goods_remarks']
        ];
        return $data;
    }

    /**
     * 报价单转订单
     * @param $offerSn
     * @param int $discountAmount
     */
    public function changeOrder($offerSn,$discountAmount=0){
        // 启动事务
        Db::startTrans();
        try {
            $offer = $this->getOffer($offerSn);
            $orderAmount = $offer['offer_total']-$discountAmount;
            if($orderAmount<0) exception('优惠金额不能大于报价金额');
            $data = [
                'customer_id'=>$offer['customer_info']['id'],
                'order_sn'=>$offer['offer_sn'],
                'offer_amount'=>$offer['offer_total'],
                'discount_amount'=>$discountAmount,
                'order_amount'=>$orderAmount,
            ];
            $orderInfo = OrderModel::create($data);
            $this->where('offer_sn',$offerSn)->update(['order_id'=>$orderInfo['id']]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            exception($e->getMessage());
            // 回滚事务
            Db::rollback();
        }
        return $orderInfo;
    }

    /**
     * 删除报价单
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function del($id){
        $info = $this->where('id',$id)->find();
        if($info['order_id']>0) exception('已转订单不允许删除');
        $this->where('id',$id)->delete();
        OfferDetailModel::where('offer_id',$id)->delete();
        return true;
    }

}
